#!/usr/bin/python3
# -*- coding: utf-8 -*-

from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative.api import DeclarativeMeta

import sys
import os

from . import settings

global Base
Base = declarative_base()
DSN = "sqlite:///{db_file}?check_same_thread=False"
engine = None
global data
data = []
global dbs
dbs = {}


def istableclass(item):
    return isinstance(item, DeclarativeMeta)


def create_tables():
    global engine
    Base.metadata.create_all(engine)


def create_session():
    global engine
    if not engine:
        init_db()
    # engine是2.2中创建的连接
    Session = sessionmaker(bind=engine)
    # 创建Session类实例
    session = Session()
    return session


def sample_data(session):
    session.add_all(data)
    session.commit()


def init_db():
    global engine
    settings.config_init()
    conf = settings.config['sqlite']
    db_exists = os.path.exists(conf.get('db_file', ''))
    if not db_exists and not os.path.exists(os.path.dirname(conf.get('db_file', ''))):
        print('floder for db file not exists: {0}'.format(
            conf.get('db_file', '')))
    else:
        db_url = DSN.format(**conf)
        # engine = create_engine(db_url, echo=True)
        engine = create_engine(db_url, echo=settings.config['sqlite']['echo'])
        create_tables()
